import { onBackPress } from '@dcloudio/uni-app'

/**
 * 自定义返回逻辑
 * @param {string} [targetUrl] - 返回要跳转的页面路径，可选
 * @param {string} [type='switchTab'] - 跳转类型: switchTab | redirectTo | reLaunch | navigateTo
 */
export function useCustomBack(targetUrl, type = 'reLaunch') {
  const goBack = () => {
    if (targetUrl) {
      switch (type) {
        case 'redirectTo':
          uni.redirectTo({ url: targetUrl })
          break
        case 'reLaunch':
          uni.reLaunch({ url: targetUrl })
          break
        case 'navigateTo':
          uni.navigateTo({ url: targetUrl })
          break
        default:
          uni.switchTab({ url: targetUrl })
      }
    } else {
      // 没传 targetUrl，就执行返回上一级
      uni.navigateBack()
    }
  }

  // App/H5 系统返回拦截
  onBackPress(() => {
    goBack()
    return true
  })

  return { goBack }
}
